//    Copyright (C) Kherty.  All rights reserved.
namespace OpenLS.Spreadsheet.StandardAddIn.Statistics
{
    internal class ChiSquaredDistribution : ContinuousDistribution
    {
        public ChiSquaredDistribution(double degreesOfFreedom)
        {
            Gamma = (new GammaDistribution(degreesOfFreedom/2.0, 2.0));
        }

        public double DegreesOfFreedom
        {
            get { return Gamma.Alpha*2.0; }
        }

        private GammaDistribution Gamma { get; set; }

        public override double CumulativeProbability(double x)
        {
            return Gamma.CumulativeProbability(x);
        }

        public override double InverseCumulativeProbability(double p)
        {
            if (p == 0)
                return 0d;
            if (p == 1)
                return double.PositiveInfinity;
            return base.InverseCumulativeProbability(p);
        }

        protected override SolverParameters GetSolverParameters(double probability)
        {
            return new SolverParameters(double.MinValue*Gamma.Beta, DomainUpperBound(probability),
                                     InitialDomain(probability));
        }

        protected double DomainUpperBound(double p)
        {
            
            if (p < .5)
                return DegreesOfFreedom;
            return double.MaxValue;
        }


        protected double InitialDomain(double p)
        {
            if (p < .5)
                return DegreesOfFreedom*.5;
            return DegreesOfFreedom;
        }
    }
}